<template>
  <el-dialog
    class="public-dialog"
    title="申请付款"
    width="80%"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
    destroy-on-close
  >
    <div class="h-[700px]">
      <payment-info :data="formvalue" ref="baseRef" />
      <detail-info v-if="id" :data="formvalue" ref="detailInfoRef" />
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? "关闭" : "取消" }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup>
import { ElMessage } from "element-plus";
import paymentInfo from "./paymentInfo/index.vue";
import detailInfo from "./detailInfo/index.vue";
import { getApplyPaymentGd, saveApplyPayment } from "../../api/index";
const route = useRoute();

const props = defineProps({
  id: { type: [Number, String, Array], default: "" },
  modelValue: { type: Boolean, default: false },
  data: { type: Object, default: () => {} },
});
const emit = defineEmits(["update:modelValue", "close", "refresh"]);
const formvalue = ref({ id: null });
const loading = ref(false);
const baseRef = ref();
const { id, data } = toRefs(props);
watch(
  () => data.value,
  (val) => {
    if (val) {
      nextTick(() => {
        formvalue.value = val || {};
      });
    }
  }
);
const detailInfoRef = ref();
const handleSave = async () => {
  try {
    loading.value = true;
    let baseInfo = await baseRef.value?.submit();
    const detailInfo = await detailInfoRef?.value?.tableDataAll();
    const isValid = detailInfo.every(
      (item) =>
        item.receive_account_name &&
        item.receive_account_number &&
        item.opening_bank
    );
    if (!isValid)
      return ElMessage.warning(
        "明细信息中的'收款账户名','收款账号','开户行'不能为空!"
      );
    baseInfo.details = detailInfo;
    const res = await saveApplyPayment({
      ...baseInfo,
    });
    if (res.code !== 200) {
      ElMessage.warning(res.message);
      return;
    }
    ElMessage.success("保存成功");
    handleClose(true);
  } catch (e) {
    if (e?.toString().includes(false)) {
      ElMessage.warning("请检查表单信息");
    }
    console.error(e);
  } finally {
    loading.value = false;
  }
};
const handleClose = async (refresh) => {
  formvalue.value = {};
  await nextTick();
  baseRef.value.resetForm();
  emit("update:modelValue", false);
  emit("close");
  if (refresh) emit("refresh");
};
</script>

<style lang="scss" scoped></style>
